using System;
using System.ComponentModel;

namespace CloudClipboardSync
{
    public class WndProcHandler: IDisposable
    {
        private readonly WinApi.WindowProcedureHandler lpfnWndProc;

        public IntPtr Handle { get; protected set; }

        public delegate void WindowProcedureHandler(IntPtr hwnd, uint uMsg, uint wparam, uint lparam);
        public event WindowProcedureHandler WindowMessageReceived;

        /// <summary>
        /// Creates the helper message window that is used
        /// to receive messages from the taskbar icon.
        /// </summary>
        public WndProcHandler()
        {
            //generate a unique ID for the window
            var windowId = "WindowMessageSink_" + DateTime.Now.Ticks;

            // Create a simple window class which is reference through
            //the messageHandler delegate
            WinApi.WindowClass wc;

            wc.style = 0;
            wc.cbClsExtra = 0;
            wc.cbWndExtra = 0;
            wc.hInstance = IntPtr.Zero;
            wc.hIcon = IntPtr.Zero;
            wc.hCursor = IntPtr.Zero;
            wc.hbrBackground = IntPtr.Zero;
            wc.lpszMenuName = "";
            wc.lpszClassName = windowId;

            lpfnWndProc = (hwnd, uMsg, wparam, lparam) =>
            {
                if (WindowMessageReceived != null)
                    WindowMessageReceived(hwnd, uMsg, wparam, lparam);

                return WinApi.DefWindowProc(hwnd, uMsg, wparam, lparam);
            };            
            wc.lpfnWndProc = lpfnWndProc;

            // Register the window class
            WinApi.RegisterClass(ref wc);

            // Create the message window
            Handle = WinApi.CreateWindowEx(0, windowId, "", 0, 0, 0, 1, 1, 0, 0, 0, 0);
            if (Handle == IntPtr.Zero)
                throw new Win32Exception();
        }

        public void Dispose()
        {
            WinApi.DestroyWindow(Handle);
        }
    }
}